package vashion.azeroth.back.controller.tran;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import vashion.azeroth.core.manager.personal.tran.PersonalDisburseManager;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.tran.pojo.PersonalDisburse;
import vashion.azeroth.core.personal.tran.pojo.PersonalDisburseExt;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshotSku;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.base.BaseService;
import vashion.azeroth.core.service.tran.PersonalDisburseService;

@Controller
@RequestMapping("/back/tran")
public class PersionalDisburseController {
	
	@Autowired
	private PersonalDisburseService disburseService;
	@Autowired
	private PersonalDisburseManager disburseManager;
	
	
	@RequestMapping("doSearch.htm")
	public String doSearch(Model model, @ModelAttribute("PersonalDisburse") PersonalDisburseExt disburse, HttpSession httpSession) {
		
		PersonalMember loginMemer = (PersonalMember)httpSession.getAttribute("member");
		if(!loginMemer.getMemberName().equals("admin")) {
			disburse.setSellerMemberName(loginMemer.getMemberName());
		}
		
		if(null == disburse.getStatus()) {
			//设置一个假值，具体查询条件在SQL里
			disburse.setStatus(1000);
		}

		int totalCount = disburseManager.getOrderManagerDisburseListCnt(disburse);
		BaseService page = new BaseService();
		page.initPages(disburse, totalCount);
		List<PersonalDisburseExt> orderList = disburseManager.getOrderManagerDisburseList(disburse);
		
		for (PersonalDisburseExt personalDisburseExt : orderList) {
			personalDisburseExt.setSkus(JSON.parseArray(personalDisburseExt.getSnapshot().getProductQuantity(), PersonalSnapshotSku.class));
			
			List<PersonalSnapshotSku> skus = personalDisburseExt.getSkus();
			int itemCount = 0;
			for (PersonalSnapshotSku sku : skus) {
				itemCount += sku.getStock();
			}
			personalDisburseExt.getSnapshot().setQuantity(itemCount);
		}
		
		model.addAttribute("orderList", orderList);
		model.addAttribute("page", page);
		
		return "/order/disburseOrdersData";
	}
	
	@RequestMapping("modifyDisburse.htm")
	@ResponseBody
	public ApiResult<PersonalDisburse> modifyDisburse(String disburseNo) {

		PersonalDisburse disburse = disburseManager.getByDisburseNo(disburseNo);
		
		return ApiResult.newSuccessResult(disburse);
	}
	
	@RequestMapping("updateDisburse.htm")
	@ResponseBody
	public ApiResult<PersonalDisburse> updateDisburse(PersonalDisburseExt param) {
		
		disburseManager.update(param);
		
		return ApiResult.newSuccessResult();
	}
	
}
